# -*- coding: utf-8 -*-
"""
@date: 2021/8/30 19:10
@file: sparse_categorical_accuracy_use.py
@author: lilong
@desc: 
"""

"""
参考：https://blog.csdn.net/qq_20011607/article/details/89213908
"""

import numpy as np
from keras import backend as K


def categorical_accuracy(y_true, y_pred):
    y_true = K.argmax(y_true, axis=-1)
    y_pred = K.argmax(y_pred, axis=-1)
    return K.cast(K.equal(y_true, y_pred), K.floatx())


def sparse_categorical_accuracy(y_true, y_pred):
    y_true_max = K.max(y_true, axis=-1)
    y_pre_argmax = K.argmax(y_pred, axis=-1)
    y_pred_argmax = K.cast(y_pre_argmax, K.floatx())
    bb = K.equal(y_true_max, y_pred_argmax)
    return K.cast(bb, K.floatx())


if __name__ == "__main__":
    tf_session = K.get_session()

    kcon = K.constant(
        [[1, 2, 0],
         [3, 4, 5]]
    )
    # print("输入张量：\n", kcon.eval(session=tf_session))

    # sum0 = K.sum(kcon, axis=0)
    # print("沿着張量0軸方向求和：\n", sum0.eval(session=tf_session))
    #
    # sum1 = K.sum(kcon, axis=1)
    # print("沿着張量1軸方向求和：\n", sum1.eval(session=tf_session))
    #
    # sum2 = K.sum(kcon)
    # print("axis缺省時，所有元素求和：\n", sum2.eval(session=tf_session))

    # y0 = K.argmax(kcon, axis=0)
    # print("沿着張量0軸方向尋找最大值索引：\n", y0.eval(session=tf_session))
    #
    # y1 = K.argmax(kcon, axis=1)
    # print("沿着張量1軸方向尋找最大值索引：\n", y1.eval(session=tf_session))
    #
    # y2 = K.argmax(kcon)
    # print("axis缺省時，默認爲-1,對應1的結果：\n", y2.eval(session=tf_session))

    # # # 测试categorical_accuracy
    # y_true = K.constant([0, 0, 1, 0])
    # y_pred = K.constant([0.02, 0.05, 0.83, 0.1])
    # y_true = K.argmax(y_true, axis=-1)
    # y_pred = K.argmax(y_pred, axis=-1)
    # print("y_true:", y_true.eval(session=tf_session))
    # print("y_pred:", y_pred.eval(session=tf_session))
    # a = K.equal(y_true, y_pred)
    # print("a:", a.eval(session=tf_session))
    # b = K.cast(a, K.floatx())
    # print("b:", b.eval(session=tf_session))

    # # 测试categorical_accuracy
    y_true = K.constant([2])  # 本身就是标签值
    y_pred = K.constant([0.02, 0.05, 0.83, 0.1])
    y_true_max = K.max(y_true, axis=-1)
    y_pre_argmax = K.argmax(y_pred, axis=-1)
    y_pred_argmax = K.cast(y_pre_argmax, K.floatx())
    bb = K.equal(y_true_max, y_pred_argmax)
    print("y_true_max:", y_true_max.eval(session=tf_session))
    print("y_pre_argmax:", y_pre_argmax.eval(session=tf_session))
    print("y_pred_argmax:", y_pred_argmax.eval(session=tf_session))
    print("bb:", bb.eval(session=tf_session))

    ll = K.cast(bb, K.floatx())
    print("ll:", ll.eval(session=tf_session))
